package org.javaboy.webflux_demo01.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        long startTime = System.currentTimeMillis();
        String s = methodExecTime();
        long endTime = System.currentTimeMillis();
        String x = "hello 方法执行耗时 " + (endTime - startTime) + " 毫秒";
        System.out.println(x);
        return s;
    }

    private String methodExecTime() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "hello";
    }

    @GetMapping("/hello2")
    public Mono<String> hello2() {
        long startTime = System.currentTimeMillis();
        Mono<String> hello2 = Mono.fromSupplier(() -> methodExecTime());
        long endTime = System.currentTimeMillis();
        String x = "hello2 方法执行耗时 " + (endTime - startTime) + " 毫秒";
        System.out.println(x);
        return hello2;
    }

    @GetMapping(value = "/userNames", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> userNames() {
        long startTime = System.currentTimeMillis();
        Flux<String> flux = Flux.fromArray(new String[]{"zhangsan", "lisi", "wangwu"}).map(s -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return s + " 你好";
        });
        long endTime = System.currentTimeMillis();
        String x = "userNames 方法执行耗时 " + (endTime - startTime) + " 毫秒";
        System.out.println(x);
        return flux;
    }
}
